package com.ate.aoligei.presenter;

import com.ate.aoligei.contract.Contract;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

/**
 * @author Ate
 * @description:
 * @date :2020/11/9 16:08
 */
public class LoginPresenter implements Contract.LoginPresenter {
    Contract.LoginView view;

    public LoginPresenter(Contract.LoginView view) {
        this.view = view;
    }

    @Override
    public void login(String username,String password) {
        goLogin(username, password, new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String body = response.body();
                try {
                    JSONObject object = new JSONObject(body);
                    int code = object.getInt("errorCode");
                    String msg = object.getString("errorMsg");
                    if (code!=-1){
                        view.onSuccess();
                    }else {
                        view.onError(msg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    private void goLogin(String username,String password,StringCallback callback){
        HashMap<String, String> map = new HashMap<>();
        map.put("username",username);
        map.put("password",password);
        map.put("repassword",password);
        //M层的注册方法
        OkGo.<String>post("https://www.wanandroid.com/user/login")
                .params(map).execute(callback);
    }
}
